package com.old.nsi_class.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.old.nsi_class.DB.Course_DB;
import com.old.nsi_class.DB.JsonResult;
import com.old.nsi_class.common.payment.WechatPaymentUtil;
import com.old.nsi_class.model.Course_model;
import com.google.gson.Gson;

@WebServlet("/Payment_api")
public class Payment_api extends HttpServlet {

    private static final long serialVersionUID = 9027554465754588101L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String whereFrom = null;
        whereFrom = request.getParameter("whereFrom");
        String UserIp = request.getRemoteAddr();
//    	微信支付
        if (whereFrom.equals("WeChatPayment")) {
            System.out.println("Payment_api WF======WeChatPayment");
            //接受参数
            String Id = request.getParameter("Id");
            String UserMail = request.getParameter("UserMail");
            //查询课程信息 ---通过课程Id
            String sql = "SELECT * from nsi_course WHERE Id=" + Id + " ;";
            List<Course_model> list = new ArrayList<Course_model>();
            list = Course_DB.CourseSearch(sql);
            String CourseSubject = list.get(0).getCourseSubject();
            String CoursePrice = list.get(0).getCoursePrice();
            //附加参数,用于验证支付是否成功
            String attach = Id + "-" + UserMail;

            String back = null;
            try {
                back = WechatPaymentUtil.WechatGetQR(CourseSubject, CoursePrice, attach);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String backJSON = "{\"code\":1,\"msg\":\"SUCCESS\",\"data\":\"" + back + "\",\"CoursePrice\":\"" + CoursePrice + "\"}";
            JsonResult.commonMethod(request, response, backJSON);


//		微信H5支付	
        } else if (whereFrom.equals("WeChatHtml5Payment")) {
            System.out.println("Payment_api WF======WeChatHtml5Payment");
            //接受参数
            String Id = request.getParameter("Id");
            String UserMail = request.getParameter("UserMail");
            //查询课程信息 ---通过课程Id
            String sql = "SELECT * from nsi_course WHERE Id=" + Id + " ;";
            List<Course_model> list = new ArrayList<Course_model>();
            list = Course_DB.CourseSearch(sql);
            String CourseSubject = list.get(0).getCourseSubject();
            String CoursePrice = list.get(0).getCoursePrice();
            //附加参数,用于验证支付是否成功
            String attach = Id + "-" + UserMail;
            String back = null;
            try {
                back = WechatPaymentUtil.WechatHTML5(CourseSubject, CoursePrice, attach, UserIp);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String backJSON = "{\"code\":1,\"msg\":\"SUCCESS\",\"data\":\"" + back + "\",\"CoursePrice\":\"" + CoursePrice + "\"}";
            JsonResult.commonMethod(request, response, backJSON);


            //	微信小程序支付-用户登录通过code获得openId
        } else if (whereFrom.equals("WeChatMiniprogramPayment")) {

            String code = request.getParameter("code");
            String price = request.getParameter("price");
            String body = request.getParameter("body");
            String attach = request.getParameter("attach");

            System.out.println("Payment_api WF======WeChatMiniprogramPayment:" + code);

            String back = null;
            try {
                back = WechatPaymentUtil.WeChatOpenId(code, price, body,attach);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String backJSON = "{\"code\":1,\"msg\":\"SUCCESS\",\"data\":" + back + "}";
            System.out.println("backJSON:" + backJSON);
            JsonResult.commonMethod(request, response, backJSON);


//		生成团购课程购买码
        } else if (whereFrom.equals("GetPurchaseCode")) {
//			数量、生成时间、课程Id、加密时间戳
            String Num = request.getParameter("Num");
            String CourseId = request.getParameter("CourseId");
//			验证时间戳
            java.util.Date currentTime = new java.util.Date();

            List<String> list = new ArrayList<>();
//				特殊格式日期
            SimpleDateFormat formatter = new SimpleDateFormat("yyMMyydd");
            String SubmitDate = formatter.format(currentTime);

            for (int i = 1; i <= Integer.parseInt(Num); i++) {
                //限定范围的随机数
                int min = 17;
                int max = 33;
                Random rand = new Random();
                int RandomNum = (rand.nextInt(max - min) + min);
                //课程随机数
                int IntCourseId = Integer.parseInt(CourseId) + RandomNum * 3;
                String PurchaseCode = RandomNum + SubmitDate + "23" + IntCourseId;
                System.out.println("PurchaseCode_10:" + PurchaseCode);
                Long num = Long.valueOf(PurchaseCode);
                String HexCode = Long.toHexString(num);
                System.out.println("PurchaseCode_16:" + HexCode);

                list.add(HexCode);
            }
            Gson gson = new Gson();
            String jsonList = gson.toJson(list);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"data\":" + jsonList + "}");

            //校验课程购买码
        } else if (whereFrom.equals("CheckPurchaseCode")) {
            //用户邮箱、PurchaseCode
            String PurchaseCode = request.getParameter("PurchaseCode");
            String UserMail = request.getParameter("UserMail");
            String sign = request.getParameter("sign");
            //判断随机数是否符合规则
            int sign01 = Integer.parseInt(sign.substring(0, 2));
            int sign02 = Integer.parseInt(sign.substring(2, 4));
            //验证时间戳
            java.util.Date currentTime = new java.util.Date();
            //验证时间戳
            SimpleDateFormat formatter02 = new SimpleDateFormat("dd");
            String SubmitDate02 = formatter02.format(currentTime);

//	    	错误状态J
            int j = -2;
            if (17 <= sign01 && sign01 <= 33) {
                if (Integer.parseInt(SubmitDate02) == sign02) {

//					解析PurchaseCode的Id
                    Long PurchaseCode_10 = Long.valueOf(PurchaseCode, 16);
                    //课程随机数
                    int RandomNum_2 = 3 * Integer.parseInt(String.valueOf(PurchaseCode_10).substring(0, 2));

                    String CourseId = String.valueOf(PurchaseCode_10 - RandomNum_2).substring(12, 17);
                    System.out.println("PurchaseCode:" + PurchaseCode + "PurchaseCode_10:" + PurchaseCode_10);
                    System.out.println("CourseId:" + CourseId);
//					购买业务执行

                    String sql02 = "insert nsi_course_user (ClassId,UserMail) values ('" + CourseId + "','" + UserMail + "'); ";
                    int i = Course_DB.insert02(sql02);
                    if (i == 1) {
                        //业务执行成功
                        System.out.println("课程购买码-购买成功");
                        j = 1;
                    } else {
                        //业务执行失败
                        j = -1;
                    }
                } else {
                    j = -3;
                    System.out.println("课程购买码 验证失败01");
                }
            } else {
                j = -4;
                System.out.println("课程购买码 验证失败02");
            }
            //成功：返回课程名
            System.out.println("验证状态：" + PurchaseCode + UserMail + sign);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"msg\":" + j + "}");


        }

    }


}
